package hbec.kettle.etl.plugins.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.LogLevel;
import org.pentaho.di.trans.Trans;

import hbec.kettle.etl.common.plugin.MetaData;
import hbec.kettle.etl.engine.conf.ParseXMLUtil;
import hbec.kettle.etl.engine.conf.TransEntityConf;
import hbec.kettle.etl.plugins.core.TransBuilder;
import hbec.kettle.etl.plugins.core.TransExecutor;

public final class Cache {
	public static Map<String, TransExecutor> transExecutorCache = new HashMap<>();
	/*
	private static Map<String, JobMeta> jobMetaCache = new HashMap<>();
	private static Map<String, Job> jobCache = new HashMap<>();
	private static Map<String, TransMeta> transMetaCache = new HashMap<>();
	private static Map<String, Trans> transCache = new HashMap<>();
	
	private static JobMeta getJobMetaCache(String name, String file) {
		return null;
	}
	
	private static Job getJobCache(String name, String file) {
		return null;
	}
	
	private static TransMeta getTransMetaCache(String name, String file) {
		return null;
	}
	
	private static Trans getTransCache(String name, String file) {
		return null;
	}
	*/
	public static synchronized TransExecutor getTransExecutorCache(TransEntityConf transEntityConf) throws KettleException {
		if (transExecutorCache.containsKey(transEntityConf.getTransName()))
			return transExecutorCache.get(transEntityConf.getTransName());
		else {
			TransExecutor transExecutor = new TransExecutor();
			//Trans trans = MetaData.getTrans(MetaData.getTransMeta(transEntityConf.getTransFile()));
			Map<String, String> fields = ParseXMLUtil.loadFieldsConfig(transEntityConf.getTransFieldsFile());
			List<String> sourceFields = new ArrayList<>();
			List<String> targetFields = new ArrayList<>();
			for (Map.Entry<String, String> e : fields.entrySet()) {
				sourceFields.add(e.getKey());
				targetFields.add(e.getValue());
			}
			
			Trans trans = MetaData.getTrans(
					TransBuilder.getSyncTableTransMeta(
							transEntityConf.getTransName(), 
							transEntityConf.getTransSrc().split("\\.")[0].trim(), 
							transEntityConf.getTransSrc().split("\\.")[1].trim(), 
							sourceFields.toArray(new String[0]), 
							transEntityConf.getTransDest().split("\\.")[0].trim(), 
							transEntityConf.getTransDest().split("\\.")[1].trim(), 
							targetFields.toArray(new String[0]))
					);
			transExecutor.setTrans(trans);
			transExecutor.setLogLevel(LogLevel.BASIC);
			transExecutorCache.put(transEntityConf.getTransName(), transExecutor);
			
			return transExecutor;
		}
	}
}
